<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button slot="left" class="filter-item" size="mini" type="primary" @click="addOrder"
          v-permission="permission.add">
          新增
        </el-button>
        <el-button slot="left" class="filter-item" size="mini" type="warning" :disabled="crud.selections.length !== 1"
          :loading="crud.copyLoading" @click="copyOrder(crud.selections)" v-permission="permission.copy">
          复制
        </el-button>
        <el-button slot="left" class="filter-item" size="mini" type="danger" :loading="crud.rejectLoading"
          icon="el-icon-remove-outline" @click="audit('PASS', '审核')" :disabled="crud.selections.length < 1"
          v-permission="permission.pass">
          审核
        </el-button>
        <el-button slot="left" class="filter-item" size="mini" :loading="crud.rejectLoading" type="success"
          icon="el-icon-circle-check" :disabled="crud.selections.length < 1" @click="audit('REJECT', '反审')"
          v-permission="permission.reject">
          反审
        </el-button>
      </crudOperation>
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="80px" v-formkey="{query:crud.toQuery}">
          <el-row :gutter="10" >
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <el-date-picker v-model="query.dataExtent" @change="getValue" type="daterange" align="right"
                  unlink-panels style="width: 100%" format="yyyy - MM - dd " value-format="yyyy-MM-dd" default-value
                  range-separator="" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="query.code" placeholder="请输入单据编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="合同名称">
                <el-input v-model="query.name" placeholder="请输入合同名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="合同类型">
                <el-select v-model="query.type" class="filter-item" clearable placeholder="请选择合同类型" style="width: 100%">
                  <el-option v-for="item in dict.t_fee_order_type" :key="item.id" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态" >
                <el-select v-model="query.orderStatus" class="filter-item" clearable placeholder="请选择状态" style="width: 100%">
                  <el-option v-for="item in dict.common_order_status" :key="item.id" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商">
                <zSelect :value.sync="query.supplierId" :label="query.supplierName" url="api/dropDown/basCustomerList"
                         :params="{isContact:'1,2'}"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <zSelect :value.sync="query.customerId" :label="query.customerName" url="api/dropDown/basCustomerList"
                         :params="{isContact:'0,2'}"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户业务员">
                <zSelect :value.sync="query.saleUserIds" url="api/dropDown/sysUserList" :params="{businessAttr:'3'}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <el-input v-model="query.customerKeyword" placeholder="输入客户关键字进行搜索"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" >
            <el-col  :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item   label="客户分类">
                <treeselect
                  style="width:  100%"
                  v-model="query.customerTypeIds"
                  :options="customerTypeList"
                  placeholder="客户分类"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'customerTypeList','customerTypeIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户区域">
                <treeselect
                  style="width:  100%"
                  v-model="query.customerAreaIds"
                  :options="areaList"
                  placeholder="客户区域"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'areaList','customerAreaIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="16" :md="16" :lg="12" :xl="12">
              <el-form-item label="备注">
                <el-input v-model="query.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" style="margin-bottom: 10px">
            <el-col :span="12" align="center">
              <rrOperation :crud="crud" />
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-dialog  title="打印预览"
                  destroy-on-close
                  v-dialogDrag
                  close-on-press-escape
                  :visible.sync="showPdf" append-to-body width="50vw">
        <j-pdf :src="pdfSrc" ></j-pdf>
      </el-dialog>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="feeContract"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.toPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                border v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
        @row-dblclick="toDetail" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column width="120" v-if="columns.visible('busDate')" prop="busDate" label="业务日期" />
        <el-table-column width="160" v-if="columns.visible('code')" prop="code" label="单据编号" />
        <el-table-column width="160" v-if="columns.visible('name')" prop="name" label="合同名称" />
        <el-table-column width="100" v-if="columns.visible('type')" prop="type" label="合同类型">
          <template slot-scope="scope">
            <span v-for="item in dict.t_fee_order_type" v-if="item.value == scope.row.type">{{ item.label }}</span>
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('supplierName')" prop="supplierName" label="供应商" />
        <el-table-column width="160" v-if="columns.visible('customerName')" prop="customerName" label="客户" />
        <el-table-column width="80" v-if="columns.visible('orderStatus')" prop="orderStatus" label="状态">
          <template slot-scope="scope">
            <span v-for="item in dict.common_order_status" v-if="item.value == scope.row.orderStatus">{{
                item.label
            }}</span>
          </template>
        </el-table-column>
        <el-table-column  v-if="columns.visible('remark')" prop="remark" label="备注" />
        <el-table-column fixed="right" v-permission="['admin', 'feeContract:edit', 'feeContract:del']" label="操作"
          width="120" align="center">
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>xin
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />

      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :visible.sync="addDialogView" :title="crud.status.title" width="500px">
        <el-form ref="addForm" :model="addForm" :rules="rules" size="small" label-width="60px">
          <el-form-item label="合同项目">
            <el-radio-group v-model="addForm.project">
              <el-radio v-for="(item, index) in dict.t_fee_contract_project" checked="checked" :label="item.value">{{
                  item.label
              }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancelAddDialog">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="submitAdd">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudFeeContract from '@/api/erp/feeContract'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import Treeselect from '@riophae/vue-treeselect'
import { getAreaTree } from '../../../api/erp/basCustomerArea'
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用合同',
  url: 'api/feeContract',
  sort: 'id,desc',
  optShow: {
    add: false,
    edit: false,
    del: true,
    copy: false,
    leadingIn: true,
    download: true,
    downloadDetail: false,
    print: true, // 打印
    printDetail: true, // 打印详情
    enable: false,
    disable: false,
    pass: false,
    reject: false
  },
  crudMethod: { ...crudFeeContract }
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  project: null,
  busDate: null,
  startDate: null,
  endDate: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  supplierId: null,
  supplierCode: null,
  supplierName: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  isPrint: null,
  printCount: null,
  seq: null,
  orderStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null
}
export default {
  name: 'FeeContract',
  components: { pagination, crudOperation, rrOperation, udOperation, jPrintConfig, Treeselect },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_fee_order_type', 'common_order_status', 't_fee_contract_project'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      permission: {
        add: ['admin', 'feeContract:add'],
        edit: ['admin', 'feeContract:edit'],
        del: ['admin', 'feeContract:del'],
        import: ['admin', 'feeContract:import'],
        export: ['admin', 'feeContract:export'],
        copy: ['admin', 'feeContract:copy'],
        upload: ['admin', 'feeContract:upload'],
        download: ['admin', 'feeContract:download'],
        pass: ['admin', 'feeContract:pass'],
        reject: ['admin', 'feeContract:reject'],
        closed: ['admin', 'feeContract:closed'],
        invalid: ['admin', 'feeContract:invalid'],
        stop: ['admin', 'feeContract:stop'],
        recover: ['admin', 'feeContract:recover'],
      },

      rules: {
        project: [
          { required: true, message: '合同项目不能为空', trigger: 'blur' }
        ]
      },
      customerTypeIds:[],
      customerTypeList:[],
      able: false,
      enable: false,
      addDialogView: false,
      addForm: {},
      showPdf:false,
      areaList: []
    }
  },
  watch: {},
  created() {
    getCustomerTypeTree({size:999}).then(res=>{
      this.customerTypeList = res
    })
    getAreaTree().then(res => {
      this.areaList = res
    })
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName1(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.query[prop] = str
    },
    getTreeName1(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName1(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    addOrder() {
      this.addDialogView = true
    },
    cancelAddDialog() {
      this.addDialogView = false
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    submitAdd() {
      const { project } = this.addForm;
      if ('rebate' === project) {
        //期初
        this.addDialogView = false
        localStorage.removeItem('feeContractRebateDetail_add')
        this.$router.push({ path: "/fee/feeContractRebateDetail/add" })
      } else if ('gift' === project) {
        //内部借款
        this.addDialogView = false
        localStorage.removeItem('feeContractGiftDetail_add')
        this.$router.push({ path: "/fee/feeContractGiftDetail/add" })
      } else if ('fee' === project) {
        //内部还款
        localStorage.removeItem('feeContractFeeDetail_add')
        this.addDialogView = false
        this.$router.push({ path: "/fee/feeContractFeeDetail/add" })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择合同项目!'
        });
      }
    },
    toDetail(row) {
      const { id, project } = row
      if ('rebate' === project) {
        //期初
        this.addDialogView = false
        this.$router.push({ path: "/fee/feeContractRebateDetail/" + id })
      } else if ('gift' === project) {
        //内部借款
        this.addDialogView = false
        this.$router.push({ path: "/fee/feeContractGiftDetail/" + id })
      } else if ('fee' === project) {
        //内部还款
        this.addDialogView = false
        this.$router.push({ path: "/fee/feeContractFeeDetail/" + id })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择合同项目!'
        });
      }
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    audit(type, msg) {
      this.crud.rejectLoading = true
      const ids = this.crud.selections.map(m => m.id)
      const data = {
        ids: ids,
        type: type
      }
      crudFeeContract.passOrReject(data).then(res => {
        if (200 === res.status) {
          this.crud.refresh()
          this.$message.success(msg + "成功")
        }
        this.crud.rejectLoading = false
      }).catch(e => {
        this.crud.rejectLoading = false
      })
    },
    copyOrder(e) {
      const { id, project } = e[0]
      if ('rebate' === project) {
        //期初
        this.crud.toCopy(id,"/fee/feeContractRebateDetail")
      } else if ('gift' === project) {
        //内部借款
        this.crud.toCopy(id,"/fee/feeContractGiftDetail")
      } else if ('fee' === project) {
        //内部还款
        this.crud.toCopy(id,"/fee/feeContractFeeDetail")
      } else {
        this.$message({
          type: 'warning',
          message: '请选择合同项目!'
        });
      }
    //   this.crud.copyLoading = true
    //   let ids = []
    //   for (let i = 0; i < e.length; i++) {
    //     ids.push(e[i].id)
    //   }
    //   crudFeeContract.copy(ids).then(res => {
    //     this.crud.copyLoading = false
    //     if (200 === res.status) {
    //       this.crud.refresh()
    //       this.$message.success("复制成功")
    //     } else {
    //       this.$message.error("复制失败")
    //     }
    //   }).catch(e=>{
    //     this.crud.copyLoading = false
    //   })
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
